package edu.jd.mainframe;

import edu.jd.aflib.AfColumnLayout;
import edu.jd.aflib.AfXLayout;
import edu.jd.authoritymanagement.AuthorityManager;
import edu.jd.eventhandler.EventExecutor;
import edu.jd.eventhandler.EventHandler;
import edu.jd.homeworkstudent.HomeworkStuDto;
import edu.jd.homeworkstudent.HomeworkStuService;
import edu.jd.homeworkteacher.CorrectHomeworkDto;
import edu.jd.homeworkteacher.HomeworkTeaService;
import edu.jd.login.CurrentUser;
import edu.jd.login.LoginService;

import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class MainFrame extends JFrame {
    JPanel root = new JPanel();
    JMenuBar menubar = new JMenuBar();
    JMenu stuMenu = new JMenu("学生");
    JMenu teaMenu = new JMenu("教师");
    JMenu adminMenu = new JMenu("管理员");
    JButton login = new JButton("登录");
    JButton logout = new JButton("退出");
    JLabel loginSuccess = new JLabel("已登录");
    JMenuItem seeHomework = new JMenuItem("查看作业");

    JPanel mainView = new JPanel();
    JLabel hkTitleLab = new JLabel("作业标题：");
    JLabel hkRequireLab = new JLabel("作业要求与内容：");
    JTextField hkTitleTF = new JTextField(20);
    JTextArea hkRequireTA = new JTextArea(10, 20);
    JLabel scoreLab = new JLabel("成绩：");
    JLabel score = new JLabel();
    JLabel feedbackLab = new JLabel("作业反馈：");
    JLabel feedback = new JLabel();
    JLabel isSubmitLab = new JLabel("是否提交：");
    JLabel submitState = new JLabel();
    JLabel roleLab = new JLabel("你的身份：");
    JLabel role = new JLabel("未登录");
    JButton releaseHomework = new JButton("发布作业");
    JButton correctHomework = new JButton("批改作业");
    JButton submitHomework = new JButton("提交作业");
    JButton nextHomework = new JButton("下一个作业");

    JPanel adminView = new JPanel();
    JMenuItem seeLog = new JMenuItem("查看日志");

    private LoginService loginService = new LoginService();
    private HomeworkTeaService homeworkTeaService = new HomeworkTeaService();
    private HomeworkStuService homeworkStuService = new HomeworkStuService();

    private List<CorrectHomeworkDto> correctHomeworkDto;
    private List<HomeworkStuDto> homework;
    private int hkIndex = 0;
    private int correctIndex = 0;

    public MainFrame(){
        this("无标题");
    }

    public MainFrame(String title){
        super(title);
        root.setLayout(new BorderLayout());
        this.setContentPane(root);

        JPanel toolBar = new JPanel();
        toolBar.setLayout(new AfXLayout());
        root.add(toolBar, BorderLayout.PAGE_START);
        /*
        menubar.add(stuMenu);
        stuMenu.add(seeHomework);

        menubar.add(teaMenu);
        teaMenu.add(new JMenuItem("成绩统计"));
        */
        menubar.add(adminMenu);
        adminMenu.add(new JMenuItem("新增用户"));
        adminMenu.add(new JMenuItem("删除用户"));
        adminMenu.add(new JMenuItem("修改用户信息"));
        adminMenu.add(seeLog);

        toolBar.add(menubar);
        toolBar.add(login);
        toolBar.add(logout);
        toolBar.add(loginSuccess);
        loginSuccess.setVisible(false);
        toolBar.add(roleLab);
        toolBar.add(role);

        mainView.setLayout(new AfColumnLayout());
        mainView.add(hkTitleLab);
        mainView.add(hkTitleTF);
        mainView.add(hkRequireLab);
        mainView.add(hkRequireTA);
        JPanel homeworkButtonPanel = new JPanel();
        homeworkButtonPanel.setLayout(new AfXLayout());
        homeworkButtonPanel.add(releaseHomework);
        homeworkButtonPanel.add(correctHomework);
        homeworkButtonPanel.add(submitHomework);
        homeworkButtonPanel.add(nextHomework);
        mainView.add(homeworkButtonPanel);
        JPanel sbPanel = new JPanel();
        sbPanel.setLayout(new AfXLayout());
        sbPanel.add(isSubmitLab);
        sbPanel.add(submitState);
        mainView.add(sbPanel);
        JPanel scPanel = new JPanel();
        scPanel.setLayout(new AfXLayout());
        scPanel.add(scoreLab);
        scPanel.add(score);
        mainView.add(scPanel);
        JPanel fbPanel = new JPanel();
        fbPanel.setLayout(new AfXLayout());
        fbPanel.add(feedbackLab);
        fbPanel.add(feedback);
        mainView.add(fbPanel);


        root.add(mainView);

        login.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                    showLoginDialog();
            }
        });
        logout.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                int role_id = CurrentUser.getCurrentUser().getRole_id();

                CurrentUser.removeCurrentUser();

                login.setVisible(true);
                loginSuccess.setVisible(false);

                hkTitleTF.setText("");
                hkRequireTA.setText("");
                submitState.setText("");
                score.setText("");
                feedback.setText("");
                role.setText("未登录");
            }
        });


        releaseHomework.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                EventExecutor executor = new EventExecutor() {
                    @Override
                    public void execute() {
                        if(hkTitleTF.getText().length()>0 && hkRequireTA.getText().length()>0){
                            int hk_id = homeworkTeaService.releaseHomework(CurrentUser.getCurrentUser().getUser_id(),
                                    hkTitleTF.getText(),
                                    hkRequireTA.getText());
                            homeworkTeaService.releaseToStudent(CurrentUser.getCurrentUser().getUser_id(), hk_id);
                            JOptionPane.showMessageDialog(root, "发布作业成功！");
                        }else{
                            JOptionPane.showMessageDialog(root, "作业标题或作业要求不能为空！");
                        }
                    }
                };
                EventHandler.handleEvent(AuthorityManager.getAuthList().get(0),
                        executor,
                        MainFrame.this);
            }
        });

        submitHomework.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                EventExecutor executor = new EventExecutor() {
                    @Override
                    public void execute() {
                        if(homework.get(hkIndex).isSubmit_state()){
                            JOptionPane.showMessageDialog(MainFrame.this, "你已经提交过了！");
                        }else{
                            DoHomeworkDialog hkDialog = new DoHomeworkDialog(MainFrame.this, homework.get(hkIndex).getHk_id());
                            if(hkDialog.isOk()){
                                initStudentInfo();
                            }
                        }
                    }
                };
                EventHandler.handleEvent(AuthorityManager.getAuthList().get(3),
                        executor,
                        MainFrame.this);
            }
        });

        correctHomework.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                EventExecutor executor = new EventExecutor() {
                    @Override
                    public void execute() {
                        CorrectDialog correctDialog = new CorrectDialog(MainFrame.this, correctHomeworkDto, correctIndex);
                        if(correctDialog.isOk()){
                            //correctIndex ++;
                            initTeacher();
                        }
                    }
                };
                EventHandler.handleEvent(AuthorityManager.getAuthList().get(1),
                        executor,
                        MainFrame.this);
            }
        });

        nextHomework.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                EventExecutor executor = new EventExecutor() {
                    @Override
                    public void execute() {
                        hkIndex ++;
                        updateHomework();
                    }
                };
                EventHandler.handleEvent(AuthorityManager.getAuthList().get(4),
                        executor,
                        MainFrame.this);
            }
        });

        seeLog.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent a){
                EventExecutor executor = new EventExecutor() {
                    @Override
                    public void execute() {
                        AdminDialog dlg = new AdminDialog(MainFrame.this);
                    }
                };
                EventHandler.handleEvent(AuthorityManager.getAuthList().get(5),
                        executor,
                        MainFrame.this);
            }
        });
    }

    public void showLoginDialog(){
        LoginDialog dlg = new LoginDialog(this);
        if(dlg.isOk()){
            login.setVisible(false);
            loginSuccess.setVisible(true);
            int role_id = CurrentUser.getCurrentUser().getRole_id();
            role.setText(CurrentUser.getCurrentUser().getRole_name());
            if(role_id==1){
                initStudentInfo();
            }
            else if(role_id == 2){
                initTeacher();
            }

        }
    }

    private void updateHomework(){
        if(hkIndex==homework.size()){
            hkIndex = 0;
        }
        HomeworkStuDto dto = homework.get(hkIndex);
        hkTitleTF.setText(dto.getHk_title());
        hkRequireTA.setText(dto.getHk_req());
        if(dto.isSubmit_state()){
            submitState.setText("已提交");
        }else{
            submitState.setText("未提交");
        }
        score.setText(dto.getScore().toString());
        feedback.setText(dto.getTea_feedback());
    }

    private void initStudentInfo(){
        homework = homeworkStuService.getHomework(CurrentUser.getCurrentUser().getUser_id());
        updateHomework();
    }

    private void initTeacher(){
        correctHomeworkDto = homeworkTeaService.getSubmittedHomework(CurrentUser.getCurrentUser().getUser_id());
    }
}
